package cn.cellcom.agent.token;

import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import cn.cellcom.agent.util.SSLClient;

public class RestTester {

	// static final String uri = "http://172.16.54.74:11001/rest/im/token";
	static final String uri = "http://www.jianyuekefu.com:8080/api.do?method=test";

	public static void main(String[] args) {
		Map<String, String> headers = new HashMap<String, String>();
		headers.put("X-Token", args[0]);
		HttpResponse result = sendRequest(uri, headers);

		if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			try {
				String string = EntityUtils.toString(result.getEntity(), "UTF-8");
				System.out.println(string);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else {
			System.out.println("error result.");
		}
	}

	/**
	 * 
	 * @param uri
	 * @param method
	 * @param headers
	 * @return
	 */
	public static HttpResponse sendRequest(String callUrl, Map<String, String> headers) {
		HttpClient client = null;
		String res = null;
		try {
			if (callUrl.startsWith("https://")) {
				client = new SSLClient();
			} else {
				client = new DefaultHttpClient();
			}
			HttpGet request = new HttpGet(callUrl);
			if (headers != null) {
				for (String key : headers.keySet()) {
					request.addHeader(key, headers.get(key));
				}
			}
			request.addHeader("Content-Type", "application/json");
			HttpResponse response = client.execute(request);
			return response;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (client != null && client.getConnectionManager() != null) {
				client.getConnectionManager().shutdown();
			}
		}
		return null;
	}
}
